using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using User.Application.Contracts.Commands;
using User.Application.Contracts.DTOs;
using User.Application.Contracts.Interfaces;

namespace User.HttpAPI.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class UserController : ControllerBase
    {
        private readonly IUserAppService _userAppService;
        private readonly ILogger<UserController> _logger;
        private readonly IMediator _mediator;
        public UserController(IUserAppService userAppService, IMediator mediator, ILogger<UserController> logger)
        {
            _userAppService = userAppService;
            _mediator = mediator;
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        [Authorize]
        [HttpGet("profile")]
        public async Task<ActionResult<UserProfileDto>> GetUserProfileAsync()
        {

            // 取 userId：通常是 NameIdentifier (ClaimTypes.NameIdentifier) 或 “sub”
            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value
                         ?? User.FindFirst("sub")?.Value;

            if (string.IsNullOrEmpty(userId))
            {
                throw new InvalidOperationException("userId missing");
            }

             _logger.LogDebug("Requesting profile for userId={UserId}", userId);
            var userProfile = await _userAppService.GetUserProfileAsync(userId);
            if (userProfile == null)
            {
                return NotFound("User profile not found");
            }

            return Ok(userProfile);
        }


        [HttpPost("register")]
        public async Task<IActionResult> RegisterAsync(RegisterUserCommand command)
        {
            var result = await _mediator.Send(command);

            return Ok(result);
        }


    }
}